package a11threadsafe3;

import a10threadsafe2.MyRunnanble;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-04-17
 * Time: 15:08
 */
public class MyThread extends Thread{
    static int ticket = 0;
    static Lock lock = new ReentrantLock();      //加static,证明创建的所有对象都共享同一把锁
    @Override
    public void run() {
        //1. 循环
        //2. 同步代码块(同步方法)
        //3. 判断共享数据是否到末尾
        //4. 判断共享数据是否到了末尾,如果没有到末尾

        //1. 循环
        while(true) {
            //2. 同步代码块(同步方法)
            //synchronized (MyRunnanble.class) {
            lock.lock();    //加锁
            try {
                //3. 判断共享数据是否到末尾
                if(ticket == 100) {
                    break;
                }else {
                    Thread.sleep(10);

                    ticket++;
                    System.out.println(Thread.currentThread().getName()+"在卖第"+ticket+"张票!!!");
                }
                //}
            }  catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();  //释放锁
            }
        }
    }
}
